using System;
using System.Data;

using SBCommon.Data;
using SBCommon.Validation;
using SecurityModule.Entity;
using System.Collections.Generic;
using SBCommon;


namespace SecurityModule.Service
{
    public class DataObjectService
    {
        
        public void Save(DataObject entity)
        {
            ValidationManager.Validate(entity);
            DataContext dc = new DataContext();
            dc.Save(entity);
        }

        
        public void Delete(int id)
        {
            DataContext dc = new DataContext();
            dc.Delete<DataObject>(id);
        }

        
        public DataObject Single(int id)
        {
            DataContext dc = new DataContext();
            DataObject entity = dc.Single<DataObject>(id);
            return entity;
        }

        //public DataSet GetAllByApplicationId(int applicationId)
        //{
        //    string sql = "select a.* from SEC_DataObject a with(nolock) "
        //        + "inner join SEC_DataObjectAndApplication b with(nolock) on a.dataobject_id=b.dataobject_id "
        //        + "inner join SEC_Application c with(nolock) on  b.application_id=c.application_id "
        //        + "where c.application_id=@applicationId "
        //        + "order by a.parent_id,a.dataobject_name";

        //    IQuery query = DataContext.CreateQuery(CommandType.Text, sql);
        //    query.AddInputParameter("@applicationId", DbType.Int32, applicationId);
        //    return query.ToDataSet<DataObject>();
        //}

        public List<DataObject> GetAllByApplicationId(int applicationId)
        {
            string sql = "select a.* from SEC_DataObject a with(nolock) "
                + "inner join SEC_DataObjectAndApplication b with(nolock) on a.dataobject_id=b.dataobject_id "
                + "inner join SEC_Application c with(nolock) on  b.application_id=c.application_id "
                + "where c.application_id=@applicationId "
                + "order by a.parent_id,a.dataobject_name";

            IQuery query = DataContext.CreateQuery(CommandType.Text, sql);
            query.AddInputParameter("@applicationId", DbType.Int32, applicationId);
            return query.ToList<DataObject>();
        }
        
        public DataSet Query(string whereClause, string orderClause, int startRowIndex, int maximumRows)
        {
            IQuery query = DataContext.CreateQuery();
            DataSet ds = query.Where(whereClause).OrderBy(orderClause)
                .Skip(startRowIndex).Take(maximumRows)
                .ToDataSet<DataObject>();
            return ds;
        }

    }
}

